//
//  UIApplication+CurrentViewController.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/15.
//

#import "UIApplication+CurrentViewController.h"

@implementation UIApplication (CurrentViewController)

+ (UIWindow *)up_currentKeyWindow {
    if (@available(iOS 13.0, *)) {
        NSSet<UIScene *> *connectedScenes = [UIApplication sharedApplication].connectedScenes;
        for (UIScene *scene in connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive && [scene isKindOfClass:[UIWindowScene class]]) {
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                for (UIWindow *window in windowScene.windows) {
                    if (window.isKeyWindow) {
                        return window;
                    }
                }
            }
        }
    }
    return [UIApplication sharedApplication].keyWindow;
}

+ (UIViewController *)up_currentViewController {
    UIWindow *keyWindow = [self up_currentKeyWindow];
    if (!keyWindow.rootViewController) {
        return nil;
    }
    
    // 确认根控制器是UPTabBarViewController
    if (![keyWindow.rootViewController isKindOfClass:NSClassFromString(@"UPTabBarViewController")]) {
        return nil;
    }
    
    // 从UPTabBarViewController开始查找
    return [self up_findFirstViewControllerStartingFrom:keyWindow.rootViewController];
}

+ (UIViewController *)up_findFirstViewControllerStartingFrom:(UIViewController *)viewController {
    // 1. 首先检查是否有模态弹出的控制器
    if (viewController.presentedViewController) {
        return [self up_findFirstViewControllerStartingFrom:viewController.presentedViewController];
    }
    
    // 2. 如果是导航控制器，返回可见的控制器
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)viewController;
        if (nav.visibleViewController) {
            return [self up_findFirstViewControllerStartingFrom:nav.visibleViewController];
        }
        return nav;
    }
    
    // 3. 如果是标签栏控制器，返回选中的控制器
    if ([viewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tab = (UITabBarController *)viewController;
        if (tab.selectedViewController) {
            return [self up_findFirstViewControllerStartingFrom:tab.selectedViewController];
        }
        return tab;
    }
    
    // 4. 如果是UPTabBarViewController，检查它的child控制器
    if ([viewController isKindOfClass:NSClassFromString(@"UPTabBarViewController")]) {
        for (UIViewController *child in [viewController.childViewControllers reverseObjectEnumerator]) {
            if (child.isViewLoaded && child.view.window) {
                return [self up_findFirstViewControllerStartingFrom:child];
            }
        }
    }
    
    // 5. 默认返回当前控制器
    return viewController;
}

@end
